package net.caixiaomi.info.interfaces;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.widget.ImageView;

import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import java.lang.ref.WeakReference;

public class SimpleEqualRatioTarget extends SimpleTarget<Bitmap> {
    private WeakReference<ImageView> weakReference;
    private int mWidth;
    private int mHeight;

    public SimpleEqualRatioTarget(ImageView imageView, int width, int height) {
        weakReference = new WeakReference<ImageView>(imageView);
        mWidth = width;
        mHeight = height;
    }

    @Override
    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
        try {
            if (weakReference != null && weakReference.get() != null) {
                if (mWidth <= 0 || mHeight <= 0)
                    return;
                int width = resource.getWidth();
                int height = resource.getHeight();
                int newWidth = mWidth;
                int newHeight = mHeight;
                // 计算缩放比例
                float scaleWidth = ((float) newWidth) / width;
                float scaleHeight = ((float) newHeight) / height;
                // 取得想要缩放的matrix参数
                Matrix matrix = new Matrix();
                matrix.postScale(scaleWidth, scaleHeight);
                // 得到新的图片
                Bitmap newbm = Bitmap.createBitmap(resource, 0, 0, width, height, matrix, true);
                ImageView imageView = weakReference.get();
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setImageBitmap(newbm);
                if (resource != null && resource.isRecycled()) {
                    resource.recycle();
                    resource = null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
